package com.loren.demo27.controller;

import com.loren.demo27.form.xml.XmlFile;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;

@RestController
public class JaxbController {

    @GetMapping(value = "/jaxb/test", produces = {"application/json;charset=utf-8"})
    public XmlFile xmlFile() throws JAXBException, IOException, XMLStreamException {
        Resource resource = new ClassPathResource("tables/WorkProcedure.xml");
        JAXBContext context = JAXBContext.newInstance(XmlFile.class);
        XMLInputFactory factory = XMLInputFactory.newFactory();
        factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader reader = factory.createXMLStreamReader(resource.getInputStream());
        Unmarshaller unmarshaller = context.createUnmarshaller();
        JAXBElement<XmlFile> unmarshal = unmarshaller.unmarshal(reader, XmlFile.class);
        return unmarshal.getValue();
    }

}
